package cn.bocweb.spinning.view.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bocweb.spinning.R;
import cn.bocweb.spinning.model.Bean.AddFavoritesBean;
import cn.bocweb.spinning.model.Bean.ErrorBean;
import cn.bocweb.spinning.model.Bean.GetAddBean;
import cn.bocweb.spinning.model.Bean.GetCommentTotalBean;
import cn.bocweb.spinning.model.Bean.InsertCommentBean;
import cn.bocweb.spinning.model.Bean.OldFangDetailBean;
import cn.bocweb.spinning.model.Bean.OldFangFavoriteBean;
import cn.bocweb.spinning.model.Bean.OldFangInsertCommentBean;
import cn.bocweb.spinning.model.Bean.OldFangTotalBean;
import cn.bocweb.spinning.model.Bean.UserBean;
import cn.bocweb.spinning.presenter.Imp.UserPresenterImp;
import cn.bocweb.spinning.presenter.UserPresenter;
import cn.bocweb.spinning.util.Constant;
import cn.bocweb.spinning.util.DeviceUtil;
import cn.bocweb.spinning.util.WXUtil;
import cn.bocweb.spinning.view.common.BaseActivity;
import cn.bocweb.spinning.view.common.ContainsEmojiEditText;
import de.greenrobot.event.EventBus;

public class InfoDetailActivity extends BaseActivity implements View.OnClickListener {

    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.info_detail_main)
    LinearLayout infoDetailMain;
    @Bind(R.id.info_detail_share)
    ImageView infoDetailShare;
    @Bind(R.id.btn_commend)
    LinearLayout btnCommend;
    @Bind(R.id.btn_send_commend)
    TextView btnSendCommend;
    @Bind(R.id.info_detail_web)
    WebView infoDetailWeb;
    @Bind(R.id.info_detail_comment_total)
    TextView infoDetailCommentTotal;
    @Bind(R.id.info_detail_comment)
    ContainsEmojiEditText infoDetailComment;

    String url;
    boolean isOldFang;
    WebSettings webSettings;
    UserPresenter userPresenter;
    PopupWindow popupWindow;
    Button btnCancel;
    String infoId;
    String userId;
    @Bind(R.id.info_detail_collect)
    ImageView infoDetailCollect;

    InputMethodManager inputMethodManager;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);

        ButterKnife.bind(this);
        EventBus.getDefault().register(this);

        initUserId();
        initToolbar();
        initIntent();
        initPopupWindow();
        initClickBtn();
        initWeb();
        initModel();

        inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    }

    @Override
    protected void onStart() {
        super.onStart();

        if (userId == null || userId.isEmpty()) {
            UserBean.DataEntity dataEntity = new UserBean.DataEntity();
            dataEntity.readInfoFromLocal(this);
            userId = dataEntity.getUserid();
        }

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    private void initUserId() {
        UserBean.DataEntity dataEntity = new UserBean.DataEntity();
        dataEntity.readInfoFromLocal(this);
        userId = dataEntity.getUserid();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant.ALL_COMMENT_INFO_DETAIL && resultCode == Constant.ALL_COMMENT_INFO_DETAIL) {
            int addCount = data.getIntExtra(Constant.ALL_COMMENT_DATA, 0);
            String count = String.valueOf(Integer.parseInt(infoDetailCommentTotal.getText().toString()) + addCount);
            infoDetailCommentTotal.setText(count);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onStop() {
        super.onStop();

    }

    private void initModel() {
        userPresenter = new UserPresenterImp();
        if (!isOldFang) {
            userPresenter.getAdd(infoId, null);
            userPresenter.getCommentTotal(infoId);
        } else {
            userPresenter.oldFangDetail(infoId, null);
            userPresenter.oldFangTotal(infoId);
        }
    }

    private void initWeb() {
        webSettings = infoDetailWeb.getSettings();
        webSettings.setJavaScriptEnabled(true);
    }

    private void initIntent() {
        Intent intent = getIntent();
        if (intent.hasExtra(Constant.INFO_DETAIL)) {
            infoId = intent.getStringExtra(Constant.INFO_DETAIL);
        } else {
            isOldFang = true;
            infoId = intent.getStringExtra(Constant.OLD_FANG_DETAIL);
        }
    }

    private void initPopupWindow() {
        View view = LayoutInflater.from(this).inflate(R.layout.window_share, null);
        btnCancel = (Button) view.findViewById(R.id.btn_window_cancel);
        view.findViewById(R.id.share_wechat_friend).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WXUtil.WXShareToFriend(url, InfoDetailActivity.this);
            }
        });

        view.findViewById(R.id.share_wechat_timeline).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WXUtil.WXShareToTimeline(url, InfoDetailActivity.this);
            }
        });

        popupWindow = new PopupWindow(view, ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.WRAP_CONTENT);
        popupWindow.setAnimationStyle(R.style.popup_window);

    }

    private void initToolbar() {
        toolbar.setNavigationIcon(R.mipmap.info_detail_exit);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(InfoDetailActivity.this, MainActivity.class));
            }
        });
    }

    private void initClickBtn() {
        infoDetailShare.setOnClickListener(this);
        btnCommend.setOnClickListener(this);
        btnSendCommend.setOnClickListener(this);
        btnCancel.setOnClickListener(this);
        infoDetailCollect.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.info_detail_share: {
                popupWindow.showAtLocation(infoDetailMain, Gravity.BOTTOM, 0, 0);
                break;
            }
            case R.id.btn_commend: {
                intent = new Intent(this, InfoAllCommentActivity.class);
                intent.putExtra(Constant.INFO_DETAIL_TO_ALL_COMMENT, isOldFang);
                intent.putExtra(Constant.INFO_DETAIL_COMMEND, infoId);
                startActivityForResult(intent, Constant.ALL_COMMENT_INFO_DETAIL);
                break;
            }
            case R.id.btn_send_commend: {
                if (userId == null || userId.isEmpty()) {
                    intent = new Intent(this, LoginAcivity.class);
                    intent.putExtra(Constant.ACTIVITY_TO_LOGIN, Constant.INFODETAIL_TO_LOGIN);
                    startActivity(intent);
                } else {
                    if (isOldFang) {
                        userPresenter.oldFangInsertComment(infoId, userId, infoDetailComment.getText().toString());
                    } else {
                        userPresenter.insertComment(infoId, userId, infoDetailComment.getText().toString());
                    }
                }
                break;
            }
            case R.id.btn_window_cancel: {
                popupWindow.dismiss();
                break;
            }
            case R.id.info_detail_collect: {
                if (userId == null || userId.isEmpty()) {
                    intent = new Intent(this, LoginAcivity.class);
                    intent.putExtra(Constant.ACTIVITY_TO_LOGIN, Constant.INFODETAIL_TO_LOGIN);
                    startActivity(intent);
                } else {
                    if (isOldFang) {
                        userPresenter.oldFangFavorite(infoId, userId);
                    } else {
                        userPresenter.addFavorites(infoId, userId);
                    }
                }
            }
        }
    }

    public void onEventMainThread(OldFangDetailBean bean) {
        if (bean.getReturn_code() == 0) {
            url = bean.getData().getBackUrl();
            infoDetailWeb.loadUrl(bean.getData().getBackUrl());
            infoDetailWeb.setWebChromeClient(new WebChromeClient() {
                @Override
                public void onProgressChanged(WebView view, int newProgress) {
                    if (newProgress == 100) {
                        hideLoading();
                    } else {
                        showLoading();
                    }
                }
            });
            infoDetailWeb.setWebViewClient(new WebViewClient() {
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    if (url.contains("http://articleid")) {
                        String infoId = url.substring(17, url.length());
                        Intent intent = new Intent(InfoDetailActivity.this, InfoDetailActivity.class);
                        intent.putExtra(Constant.INFO_DETAIL, infoId);
                        startActivity(intent);
                        return true;
                    }
                    return super.shouldOverrideUrlLoading(view, url);
                }
            });
            if (bean.getData().getStatus() == 1) {
                infoDetailCollect.setImageResource(R.mipmap.info_detail_collected);
            } else {
                DeviceUtil.MyToast(this, bean.getMsg());
            }
        }
    }

    public void onEventMainThread(OldFangTotalBean bean) {
        if (bean.getReturn_code() == 0) {
            infoDetailCommentTotal.setText(String.valueOf(bean.getData()));
        } else {
            DeviceUtil.MyToast(this, bean.getMsg());
        }
    }

    //获得h5地址
    public void onEventMainThread(GetAddBean bean) {
        if (bean.getReturn_code() == 0) {
            url = bean.getData().getBackUrl();
            infoDetailWeb.loadUrl(bean.getData().getBackUrl());
            infoDetailWeb.setWebChromeClient(new WebChromeClient() {
                @Override
                public void onProgressChanged(WebView view, int newProgress) {
                    if (newProgress == 100) {
                        hideLoading();
                    } else {
                        showLoading();
                    }
                }
            });
            infoDetailWeb.setWebViewClient(new WebViewClient() {
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    if (url.contains("http://articleid%3D")) {
                        String infoId = url.substring(19, url.length() - 1);
                        Intent intent = new Intent(InfoDetailActivity.this, InfoDetailActivity.class);
                        intent.putExtra(Constant.INFO_DETAIL, infoId);
                        startActivity(intent);
                        return true;
                    }
                    return super.shouldOverrideUrlLoading(view, url);
                }
            });
            if (bean.getData().getStatus() == 1) {
                infoDetailCollect.setImageResource(R.mipmap.info_detail_collected);
            }
        } else {
            DeviceUtil.MyToast(this, bean.getMsg());
        }
    }

    //获得评论数量
    public void onEventMainThread(GetCommentTotalBean bean) {
        if (bean.getReturn_code() == 0) {
            infoDetailCommentTotal.setText(String.valueOf(bean.getData()));
        } else {
            DeviceUtil.MyToast(this, bean.getMsg());
        }
    }

    //发送评论
    public void onEventMainThread(InsertCommentBean bean) {
        DeviceUtil.MyToast(this, bean.getMsg());
        if (bean.getReturn_code() == 0) {

            Intent intent = new Intent(this, InfoAllCommentActivity.class);
            intent.putExtra(Constant.INFO_DETAIL_COMMEND, infoId);
            startActivity(intent);
            infoDetailComment.setText("");
            String count = String.valueOf(Integer.parseInt(infoDetailCommentTotal.getText().toString()) + 1);
            infoDetailCommentTotal.setText(count);
        }
    }

    public void onEventMainThread(OldFangInsertCommentBean bean) {
        DeviceUtil.MyToast(this, bean.getMsg());
        if (bean.getReturn_code() == 0) {

            Intent intent = new Intent(this, InfoAllCommentActivity.class);
            intent.putExtra(Constant.INFO_DETAIL_COMMEND, infoId);
            intent.putExtra(Constant.INFO_DETAIL_TO_ALL_COMMENT, isOldFang);
            startActivity(intent);
            infoDetailComment.setText("");
            String count = String.valueOf(Integer.parseInt(infoDetailCommentTotal.getText().toString()) + 1);
            infoDetailCommentTotal.setText(count);
        }
    }

    //收藏资讯
    public void onEventMainThread(AddFavoritesBean bean) {
        DeviceUtil.MyToast(this, bean.getMsg());
        if (bean.getReturn_code() == 0) {
            infoDetailCollect.setImageResource(R.mipmap.info_detail_collected);
        }
    }


    public void onEventMainThread(OldFangFavoriteBean bean) {
        DeviceUtil.MyToast(this, bean.getMsg());
        if (bean.getReturn_code() == 0) {
            infoDetailCollect.setImageResource(R.mipmap.info_detail_collected);
        }
    }

    public void onEventMainThread(ErrorBean bean) {
        hideLoading();
        DeviceUtil.MyToast(this, bean.getErrorMsg());
    }

    private View.OnKeyListener onKeyListener = new View.OnKeyListener() {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                /*隐藏软键盘*/
                if (inputMethodManager.isActive()) {
                    inputMethodManager.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
                }
                return true;
            }
            return false;
        }
    };
}
